package.cpath = "/e/workspace/xbit?.so;;"

function _arrangeAids(areas)
    local res = {}
    local json = require("cjson")
    for k,area in pairs(areas) do
        local id = tostring(area["id"])
        local pid = tostring(area["pid"])
        if not res[id] then
            res[id] = {}
        end

        if  pid ~= "0" then
            if not res[pid] then
                res[pid] = {id}
            else
                res[pid][#(res[pid]) + 1] = id
            end
        end
    end

    
    return res
end

function _getAids(areas, res)
    for id,childrenIds in pairs(areas) do
        _getAid(id, childrenIds, areas, res)
    end
end

function _getAid(id, childrenIds, areas, res)
    if #childrenIds == 0 then
        res[id] = {id}
    else
        for i, v in pairs(childrenIds) do
            if res[v] then
                res[id] = util.append(res[id], res[v])
            else
                _getAid(v, area[v], areas, res)
            end
        end
    end
end

local areas = {
	["4"] = {"1","2","3"},
	["3"] = {},
	["5"] = {"4"},
	["2"] = {},
	["1"] = {}
}
print(_arrangeAids(areas))
